package hmis.pos.Service.ServiceImpl;

import hmis.pos.Base.BaseService.Impl.BaseServiceImpl;
import hmis.pos.Common.pojo.ApiResponse;
import hmis.pos.Common.vo.Order.OrderAndOrderDetail;
import hmis.pos.Common.vo.Order.OrderAndTypeAndNumber;
import hmis.pos.Common.vo.SearchPrice.TypeAndDate;
import hmis.pos.Common.vo.Order.TypeAndNumber;
import hmis.pos.Entity.Order;
import hmis.pos.Entity.OrderDetail;
import hmis.pos.Entity.RoomPrice;
import hmis.pos.Repository.OrderRepository;
import hmis.pos.Repository.RoomPriceRepository;
import hmis.pos.Service.OrderDetailService;
import hmis.pos.Service.OrderService;
import hmis.pos.Service.RoomPriceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static hmis.pos.Common.Constant.OtherConstant.ORDERDETAIL_CANCEL;
import static hmis.pos.Common.Constant.OtherConstant.ORDERDETAIL_WAIT;

@Service
public class OrderServiceImpl extends BaseServiceImpl<Order,OrderRepository> implements OrderService {
    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private RoomPriceRepository roomPriceRepository;

    @Autowired
    private  RoomPriceService roomPriceService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Override
    public Order save(OrderAndTypeAndNumber orderAndTypeAndNumber) {
        Order order = orderAndTypeAndNumber.getOrder();
        List<TypeAndNumber> typeAndNumberList = orderAndTypeAndNumber.getTypeAndNumbersList();

        List<OrderDetail> orderDetailList = new ArrayList<>();
        List<RoomPrice> roomPrices = new ArrayList<>();

        Date in_time = order.getIn_time();
        Date out_time = order.getOut_time();

        double total = 0;

        boolean isEmpty = false;

        for(TypeAndNumber typeAndNumber:typeAndNumberList){
            if(isEmpty) return null;

            OrderDetail orderDetail = new OrderDetail();
            String type = typeAndNumber.getType();
            int roomnumber = typeAndNumber.getNumber();
            //TypeAndDate typeAndDate = new TypeAndDate();
            //typeAndDate.setType(type);
            //typeAndDate.setIn_time(in_time);
            //typeAndDate.setOut_time(out_time);
            double surtotal = 0;

            //取最少可预订数
            List<RoomPrice> roomPriceList = roomPriceRepository.findByTypeAndDateBetween(type,in_time,out_time);

            int minSurplus = 0;
            if(roomPriceList.size()!=0){
                minSurplus = roomPriceList.get(0).getSurplus();
            }else{ isEmpty = true; return null;}
            for(RoomPrice roomPrice : roomPriceList){
                if(roomPrice.getSurplus()<minSurplus)
                    minSurplus = roomPrice.getSurplus();
            }
            if(minSurplus==0||minSurplus<roomnumber){isEmpty = true;return null ;}

            //减少可预订数量，增加预定数量，计算金额
            for(RoomPrice roomPrice : roomPriceList){
                roomPrice.setSurplus(roomPrice.getSurplus()-roomnumber);
                roomPrice.setReservationcount(roomPrice.getReservationcount()+roomnumber);
                surtotal += roomPrice.getPrice();

                roomPrices.add(roomPrice);
            }

            //设置订单明细
            if(!isEmpty){
                orderDetail.setSubtotal(surtotal);
                orderDetail.setType(type);
                orderDetail.setRoomnumber(roomnumber);
                orderDetail.setStatus(ORDERDETAIL_WAIT);//状态

                //roomPrices.addAll(roomPriceList);
                orderDetailList.add(orderDetail);
            }
        }

        if(isEmpty)return null;

        //计算总金额
        for(OrderDetail orderDetail:orderDetailList){
            total +=orderDetail.getSubtotal();
        }
        order.setTotal(total);

        //生成订单，添加订单明细，修改房间价格可预订数
        order.setStatus("未付款");
        Order newOrder = orderRepository.save(order);
        String id = newOrder.getId();
        for(OrderDetail orderDetail:orderDetailList){
            orderDetail.setOrderid(id);
            orderDetailService.save(orderDetail);
        }
        for(RoomPrice roomPrice:roomPrices){
            roomPriceService.update(roomPrice);
        }
        return newOrder;

    }

    @Override
    public Order savePayMessage(Order order) {
        return orderRepository.save(order);
    }

    @Override
    public List<OrderAndOrderDetail> findAllOrder(){


        List<Order> orderList = orderRepository.findAll();

        return becomeOrderAndOrderDetail(orderList);
    }

    @Override
    public ApiResponse<OrderAndOrderDetail> renew(Order order) {
        //更新订单只能更新订单的顾客，电话号码，状态

        if(("").equals(order.getApplicant()))return new ApiResponse<OrderAndOrderDetail>(0,"顾客名不能为空！");

        //判断是否为正确号码
        boolean isNumber = false;
        String phone = order.getPhone();
        for(int i=0;i<phone.length();i++){
            char c = phone.charAt(i);
            if(!(c>='0')&&(c<='9')){
                isNumber = false;
                break;
            }else isNumber = true;
        }
        if((!(isNumber))||(phone.length()!=11))return new ApiResponse<OrderAndOrderDetail>(0,"请输入正确的手机号码！");

        //更新订单信息
        Order newOrder = this.update(order);

        List<OrderDetail> orderDetailList = orderDetailService.findByOrder(newOrder);
        OrderAndOrderDetail orderAndOrderDetail = new OrderAndOrderDetail();
        orderAndOrderDetail.setOrder(newOrder);
        orderAndOrderDetail.setOrderDetailList(orderDetailList);

        return new ApiResponse<OrderAndOrderDetail>(1,"更新订单信息成功！",orderAndOrderDetail);


    }

    @Override
    public List<OrderAndOrderDetail> findByToday(Date today){

        List<Order> orderList = orderRepository.findByToday(today);

        return becomeOrderAndOrderDetail(orderList);
    }

    @Override
    public List<OrderAndOrderDetail> findByToday2() {
        List<Order> orderList = orderRepository.findByToday2();

        return becomeOrderAndOrderDetail(orderList);
    }

    @Override
    public List<OrderAndOrderDetail> findByStatus(String status) {
        List<Order> orderList = orderRepository.findByStatus(status);

        return becomeOrderAndOrderDetail(orderList);
    }

    @Override
    public ApiResponse<Order> cancel(Order order) {
        List<OrderDetail> orderDetailList = orderDetailService.findByOrder(order);
        if(order.getStatus().equals("已取消"))return new ApiResponse<Order>(0,"订单已是取消状态！");
        if(order.getStatus().equals("已付款"))return new ApiResponse<Order>(0,"订单已付款，不能取消！");
        if(order.getStatus().equals("进行中"))return new ApiResponse<Order>(0,"订单正在进行中，不能取消！");
        else{
            order.setStatus("已取消");
            for(OrderDetail orderDetail : orderDetailList){
                orderDetail.setStatus(ORDERDETAIL_CANCEL);
                orderDetailService.update(orderDetail);
            }
            Order newOrder = this.update(order);

            //更改价格表的可预订数和预定数，增加取消预订记数
            Date in_time = order.getIn_time();
            Date out_time = order.getOut_time();
            for(OrderDetail orderDetail : orderDetailList){
                List<RoomPrice> roomPriceList = roomPriceRepository.findByTypeAndDateBetween(orderDetail.getType(),in_time,out_time);
                for(RoomPrice roomPrice : roomPriceList){
                    int cancelNumber = orderDetail.getRoomnumber();                                 //取消的房间数
                    roomPrice.setSurplus(roomPrice.getSurplus()+cancelNumber);                      //修改剩余可预订数
                    roomPrice.setReservationcount(roomPrice.getReservationcount()-cancelNumber);    //减少已预订数
                    roomPriceService.update(roomPrice);                                             //更新数据库表
                }
            }

            return new ApiResponse<Order>(1,"成功取消订单！",newOrder);
        }
    }

    @Override
    public List<OrderAndOrderDetail> findByYear() {
        List<Order> orderList = orderRepository.findByYear();

        return becomeOrderAndOrderDetail(orderList);

    }

    @Override
    public List<OrderAndOrderDetail> findByMonth() {
        List<Order> orderList = orderRepository.findByMonth();

        return becomeOrderAndOrderDetail(orderList);
    }

    @Override
    public List<OrderAndOrderDetail> findByWeek() {
        List<Order> orderList = orderRepository.findByWeek();

        return becomeOrderAndOrderDetail(orderList);
    }

    public List<OrderAndOrderDetail> becomeOrderAndOrderDetail(List<Order> orderList){
        List<OrderAndOrderDetail> orderAndOrderDetailList = new ArrayList<>();

        //查找订单详情，加入订单
        for(Order order:orderList){
            OrderAndOrderDetail orderAndOrderDetail = new OrderAndOrderDetail();
            List<OrderDetail> orderDetailList = orderDetailService.findByOrder(order);

            orderAndOrderDetail.setOrder(order);
            orderAndOrderDetail.setOrderDetailList(orderDetailList);
            orderAndOrderDetailList.add(orderAndOrderDetail);
        }

        return orderAndOrderDetailList;
    }

}
